﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ITViet.Web.App_Code;
using ITViet.Domains;
using ITViet.Services;
using DevExpress.Web.ASPxGridView;
using System.Data;

namespace ITViet.Web.Admin
{
  public partial class CustomerContactDetail : AdminBasePage
  {
    #region Properties
    protected string UploadCompleteFunction = "attachFile";
    protected string UploadSessionName = SessionName.UploadContainPostedFile;
    protected string UploadFolder = FolderDirector.TempFolder;

    private string m_innerError = string.Empty;

    internal override int RequiredPermission
    {
      get
      {
        return (int)FunctionList.CustomerContact;
        //return -1;
      }
    }

    private string OpinionType
    {
      get
      {
        string type = string.Empty;
        if (Request.QueryString["t"] != null)
          type = Request.QueryString["t"].ToString().ToUpper();
        return type;
      }
    }

    private int OpinionId
    {
      get
      {
        int id = -1;
        if (Request.QueryString["id"] != null)
          id = Convert.ToInt32(Request.QueryString["id"].ToString());
        return id;
      }
    }
    #endregion

    #region Method
    protected void Page_Load(object sender, EventArgs e)
    {
      if (!IsPostBack && !IsCallback)
      {
        Session[SessionName.EmailAttachFile] = null;
        LoadOpinion();
        BindFileGrid();
      }
    }
    protected void LoadOpinion()
    {
      CustomerOpinion op = new CustomerOpinionService().GetById(OpinionId);
      if (op != null && op.Id > 0)
      {
        lblOpinionContent.Text = op.Opinion;
        txtTo.Text = op.Email;
        txtTo.Enabled = false;
        if (!String.IsNullOrEmpty(op.Title))
          txtSubject.Text = Resources.Strings.Re + op.Title;
      }
    }
    private void BindFileGrid()
    {
      DataTable tbl = null;
      if (Session[SessionName.UploadFolder] == null)
        Session[SessionName.UploadFolder] = UploadFolder;
      if (Session[SessionName.EmailAttachFile] != null)
        tbl = Session[SessionName.EmailAttachFile] as DataTable;
      if (tbl == null)
      {
        tbl = new DataTable("Attachment");
        tbl.Columns.Add(new DataColumn(("FileName"), Type.GetType("System.String")));
        tbl.Columns.Add(new DataColumn(("FilePath"), Type.GetType("System.String")));
        tbl.PrimaryKey = new DataColumn[] { tbl.Columns["FilePath"] };
        Session[SessionName.EmailAttachFile] = tbl;
      }
      gvFile.DataSource = tbl;
      gvFile.DataBind();
    }
    private string SendNewsletter()
    {
      try
      {
        string[] toEmails = null;
        string[] ccEmails = null;
        string[] bccEmails = null;
        string[] attchment = null;
        string subject = txtSubject.Text;
        string content = htmlEditor.Html;
        string emails = string.Empty;

        //To Email
        emails = txtTo.Text;
        if (emails.EndsWith(";"))
          emails = emails.Remove(emails.Length - 1);
        if (!string.IsNullOrEmpty(emails))
          toEmails = emails.Split(';');

        //Cc Email
        //emails = cbxCC.Text;
        //if (emails.EndsWith(";"))
        //    emails = emails.Remove(emails.Length - 1);
        //if (!string.IsNullOrEmpty(emails))
        //    ccEmails = emails.Split(';');

        //Bcc Email
        //emails = cbxBCC.Text;
        //if (emails.EndsWith(";"))
        //    emails = emails.Remove(emails.Length - 1);
        //if (!string.IsNullOrEmpty(emails))
        //    bccEmails = emails.Split(';');

        //Attachment
        if (gvFile.VisibleRowCount > 0)
        {
          attchment = new string[gvFile.VisibleRowCount];
          for (int i = 0; i < gvFile.VisibleRowCount; i++)
          {
            string filePath = gvFile.GetRowValues(i, "FilePath").ToString();
            attchment[i] = filePath;
          }
        }

        System.Net.Mail.MailMessage message = SendMail.PrepareMailMessage(toEmails, ccEmails, bccEmails, subject, content, attchment);
        string status = SendMail.StartSendMail(message);
        if (status == "SUCCESS")
        {
          CustomerOpinion op = new CustomerOpinionService().GetById(OpinionId);
          if (op != null && op.Id > 0)
          {
            op.IsActive = true;
            new CustomerOpinionService().Save(op);
          }
        }
        //if (attchment != null)
        //{
        //  foreach (string filePath in attchment)
        //  {
        //    if (File.Exists(filePath))
        //    {
        //      File.Delete(filePath);
        //    }
        //  }
        //}
      }
      catch (Exception ex)
      {
        WriteLog("Newsletter.aspx::Send Newsletter", ex);
        return Resources.Messages.ERR0030;
      }
      return string.Empty;
    }

    #endregion

    #region Event
    protected void ctrlCallback_Callback(object source, DevExpress.Web.ASPxCallback.CallbackEventArgs e)
    {
      e.Result = SendNewsletter();
    }

    protected void gvFile_CustomCallback(object sender, ASPxGridViewCustomCallbackEventArgs e)
    {
      string[] para = e.Parameters.Split('|');
      if (para[0] == "Save")
      {
        string file = para[1];
        DataTable tbl = Session[SessionName.EmailAttachFile] as DataTable;
        if (tbl == null)
          return;
        string uploadedList = string.Empty;
        if (Session[SessionName.UploadReturnFiles] != null)
          uploadedList = Session[SessionName.UploadReturnFiles].ToString();
        if (!string.IsNullOrEmpty(uploadedList))
        {
          string[] fileList = uploadedList.Split(';');
          if (fileList != null)
          {
            for (int i = 0; i < fileList.Length; i++)
            {
              if (string.IsNullOrEmpty(fileList[i]))
                continue;
              int count = fileList[i].LastIndexOf('/') + 1;
              string fileName = fileList[i].Remove(0, count);
              count = fileName.IndexOf('_') + 1;
              fileName = fileName.Remove(0, count);
              DataRow newFile = tbl.NewRow();
              newFile["FileName"] = fileName;
              newFile["FilePath"] = MapPath("../" + fileList[i]);
              tbl.Rows.Add(newFile);

            }
          }
          ClearSession(new string[] { SessionName.UploadReturnFiles, SessionName.UploadContainPostedFile });
          BindFileGrid();
        }
      }
    }

    protected void gvFile_RowDeleting(object sender, DevExpress.Web.Data.ASPxDataDeletingEventArgs e)
    {
      ASPxGridView grid = sender as ASPxGridView;
      DataTable tbl = Session[SessionName.EmailAttachFile] as DataTable;
      if (tbl != null)
      {
        string filePath = e.Keys["FilePath"].ToString();
        DataRow row = tbl.Rows.Find(filePath);
        if (row != null)
          tbl.Rows.Remove(row);
      }
      e.Cancel = true;
      grid.CancelEdit();
      BindFileGrid();
    }


    #endregion
  }
}
